package com.tangyuan.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tangyuan.common.enums.Genre;
import com.tangyuan.common.result.Result;
import com.tangyuan.common.result.ResultCodeEnum;
import com.tangyuan.common.util.CollUtils;
import com.tangyuan.dto.UserActionDto;
import com.tangyuan.enums.ActionConstant;
import com.tangyuan.model.User;
import com.tangyuan.model.UserLike;
import com.tangyuan.user.mapper.UserLikeMapper;
import com.tangyuan.user.mapper.UserMapper;
import com.tangyuan.user.service.UserLikeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 小梁
 * @since 2020-12-03
 */
@Service
@Slf4j
public class UserLikeServiceImpl extends ServiceImpl<UserLikeMapper, UserLike> implements UserLikeService {
    @Autowired
    private UserLikeMapper userLikeMapper;


    @Autowired
    private UserMapper userMapper;


    /**
     * 更新潜在因子userLike表
     *
     * @return 1成功 0失败
     */
    @Override
    public int updateUser(UserActionDto dto) {
        if(dto.getCategoryId() == null || dto.getCategoryId() == 0){
            log.info("该视频没有分类,不进行行为加分:{}",dto.getMovieId());
            return 0;
        }
        double score;
        float value;
        UserLike userLike = userLikeMapper.selectByUserId(dto.getUserId());
        if (userLike == null) {
            userLike = new UserLike();
            userLike.setUserId(dto.getUserId());
        }
        score = UserLike.getMethod(userLike,dto.getCategoryId()) + (dto.getGrade() * ActionConstant.GRADE_WEIGHT_F + dto.getCollection() * ActionConstant.COLLECTION_WEIGHT_F + dto.getThump() * ActionConstant.THUMP_WEIGHT_F) * 1.0; //score=sum+1.0*行为分
        value = (float) score;
        UserLike.setMethod(userLike,dto.getCategoryId(), value);
        boolean b = this.saveOrUpdate(userLike);
        if(b){
            return 1;
        }
        return 0;

    }
    /**
     * 插入一条潜在因子记录到userLike
     *
     * @param userId
     * @return 1成功 0失败
     */
    @Override
    public int addUser(int userId) {
        UserLike userLike = new UserLike((long) userId, 0F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, 0F,0F,0F,0F,0f,0f,0f);
        return userLikeMapper.insert(userLike);
    }

    /**
     * 得到所有的UserLike信息
     *
     * @return List<UserLike>
     */
    @Override
    public List<UserLike> getUserLikeList() {
        List<UserLike> userLikes = userLikeMapper.selectList(new QueryWrapper<UserLike>().orderByAsc("user_id"));
        return userLikes;
    }

    @Override
    public Result<String> register(int id) {
        int i = this.addUser(id);
        //成功
        if (i > 0) {
            return Result.ok();
        } else {
            // 原错误码 407，备注一下，防止修改后有问题 2024/4/25 下午1:42 By Wesin
            return Result.build(null, ResultCodeEnum.USER_EXIST);
        }
    }

    @Override
    public Result regis(Long id) {
        int i = this.addUser(id.intValue());
        //成功
        if (i > 0) {
            return Result.ok();
        } else {
            return Result.build(null, ResultCodeEnum.USER_EXIST);
        }
    }

    @Override
    public List<UserLike> selectUserLikeListByIds(List<Long> ids) {
        if(CollectionUtils.isEmpty(ids)){
            return new ArrayList<>();
        }
        QueryWrapper<UserLike> wrap = new QueryWrapper<>();
        wrap.lambda().in(UserLike::getUserId, ids);
        wrap.lambda().orderByAsc(UserLike::getUserId);
        return userLikeMapper.selectList(wrap);
    }

    @Override
    public Result addUserLikeByHorizontalTab(Long userId, List<String> horizontalTabList) {
        if (userId == null) {
            return Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        }
        User user = userMapper.selectById(userId);
        if (user == null){
            return Result.build(null, ResultCodeEnum.USER_NOT_EXIST);
        }
        if (CollUtils.isEmpty(horizontalTabList)) {
            return Result.build(null, ResultCodeEnum.ARGUMENT_VALID_ERROR);
        }
        // 创建或获取UserLike对象
        UserLike userLike = userLikeMapper.findByUserId(userId);
        if (userLike == null){
            userLike = new UserLike();
            userLike.setUserId(userId);
            extracted(horizontalTabList, userLike);
            // 保存到数据库
            userLikeMapper.insert(userLike);
            user.setIsFirstLogin(0);
            userMapper.updateById(user);
            return Result.ok();
        }
        extracted(horizontalTabList, userLike);
        LambdaUpdateWrapper<UserLike> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(UserLike::getUserId, userId);
        userLikeMapper.update(userLike, lambdaUpdateWrapper);
        user.setIsFirstLogin(0);
        userMapper.updateById(user);
        return Result.ok();
    }

    @Override
    public UserLike selectUserById(Long id) {
        if(id == null || id == 0){
            return null;
        }
        return baseMapper.selectById(id);
    }

    @Override
    public int getLikeType(Long id) {
        UserLike like = this.selectUserById(id);
        return UserLike.getMaxMethod(like);
    }

    private void extracted(List<String> horizontalTabList, UserLike userLike) {
        // 遍历并处理每个喜好字符串
        Set<Genre> validGenres = new HashSet<>();
        for (String horizontalTab : horizontalTabList) {
            // 处理字符串并尝试获取对应的Genre
            String cleanGenreName = horizontalTab.replace("type_", "").replace("_value", "");
            Genre genre = Genre.fromString(cleanGenreName)
                    .orElse(null);

            // 如果找到有效的Genre，添加到集合中
            if (genre != null) {
                validGenres.add(genre);
            }
        }

        // 检查是否有有效的Genre，如果没有，抛出异常
        if (validGenres.isEmpty()) {
            throw new IllegalArgumentException("No valid genre found in the provided horizontal tabs.");
        }

        // 应用所有找到的有效Genre
        for (Genre genre : validGenres) {
            genre.apply(userLike);
        }
    }
}
